home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8059 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  76 lines

  1. Path: s02.pavilion.co.uk!usenet
  2. From: AJRobb@pavilion.co.uk (Andy J Robb)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointer arithmetic
  5. Date: Fri, 01 Mar 1996 06:56:58 GMT
  6. Organization: Pavilion Internet plc
  7. Message-ID: <4h672i$329@s02.pavilion.co.uk>
  8. References: <4h2r55$er@s3.iway.fr>
  9. NNTP-Posting-Host: poolc53.pavilion.co.uk
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Pascal Terracol <assetsto@pratique.fr> wrote:
  13.  
  14. > Hello,
  15.  
  16. >this sample code have been correctly working on a pc 80286 processor
  17.  
  18. >I put it on a mac and the pointers seems to act differently...
  19. >any idea about that ? 
  20.  
  21. >     int size, n1, n2 ;
  22. >     Point  *p_debut, *p1, *p2 ;                      /* "vecteur" de translation des adr  */
  23.  
  24. I'm assuming that l includes pointers:
  25.  
  26. struct {
  27.   Point *p1, *p2;
  28. ...
  29. } *l;
  30.  
  31. >...
  32.  
  33. >      n1 = (int) (l->p1)/sizeof(Point) ;
  34. >         n2 = (int) (l->p2)/sizeof(Point) ;
  35. >        
  36. >            p1 = p_debut + n1 ;
  37. >            p2 = p_debut + n1 ;
  38. >...
  39.  
  40. To make this work you need a datum for l->p1 and l->p2.  The above
  41. code implicitly uses NULL as the datum (an unlikely event).  It does
  42. not have to work under ISO/ANSI (it may have worked under K&R where
  43. int and pointers were interchangable).  Syntactically, what you have
  44. is similar to:
  45.  
  46.     n1 = l->p1 - (Point*)0;
  47.     n2 = l->p2 - (Point*)0;
  48.  
  49. If you were to include a datum (Point *p_debut;) within *l, then:
  50.  
  51.     n1 = l->p1 - l->p_debut;
  52.     n2 = l->p2 - l->p_debut;
  53.  
  54. As an asside, be aware that the whole ethos of this pointer arithmetic
  55. for non-simple types becomes dubious under C++ (as sizeof(Point) may
  56. not be the size of the element which Point* is pointing to.)  To be
  57. "safe" you should define an array of pointers (which are a simple type
  58. and, therefore, safe to use with indexing arithmetic) and initialize
  59. each of these to point to individual structures.  The extra level of
  60. dereferencing will be offset by the simpler pointer arithmetic.
  61.  
  62. Au revoir,
  63.  
  64.  
  65. -----BEGIN PGP PUBLIC KEY BLOCK-----
  66. Version: 2.6.2i
  67.  
  68. mQCNAy/MpRwAAAEEAOt6uBYqT8yv9EmqNhK8m6v+bYi8QjnGW3Bo6iU1gsMj5pa6
  69. MHgq99c8deADbE3cbJ6uZS9v5pZE3WCf6HCQjlB5iULA5RZzMdAumd/WUzuL9UT3
  70. B44D9EqqFIL79FlYb56v4oKFqFp1/J2bIpYUwnUvabGzGjdLrpPl4P16x9sNAAUR
  71. tCNBbmR5IEogUm9iYiA8QUpSb2JiQHBhdmlsaW9uLmNvLnVrPrQhQW5keSBSb2Ji
  72. IDxBSlJvYmJAcGF2aWxpb24uY28udWs+
  73. =/wVD
  74. -----END PGP PUBLIC KEY BLOCK-----
  75.  
  76.